package com.xmy.cultivate.controller;

import com.xmy.cultivate.constant.MessageType;
import com.xmy.cultivate.context.ContextMessageFactory;
import com.xmy.cultivate.util.XmlUtils;
import com.xmy.cultivate.utils.AccessAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/weChar")
public class WeCharController {

    private String token = "xmyerp";

    @Autowired
    private ContextMessageFactory contextMessageFactory;

    @GetMapping
    public String getWeChar(@RequestParam String signature,
                            @RequestParam String timestamp,
                            @RequestParam String nonce,
                            @RequestParam String echostr) {
        //System.out.println("signature :" + signature);
        //System.out.println("timestamp :" + timestamp);
        //System.out.println("nonce :" + nonce);
        //System.out.println("echostr :" + echostr);
        if (AccessAuthentication.of(token, timestamp, nonce, signature).checkSignature()) {
            return echostr;
        }
        return null;
    }

    @PostMapping
    public String post(@RequestBody String message) throws Exception {
        //System.out.println("接收到微信公众平台消息：" + message);
        Map<String, Object> stringObjectMap = XmlUtils.xmlStrToMap(message);
        //System.out.println("msgType");
        MessageType msgType = MessageType.getType(stringObjectMap.get("MsgType").toString());
        return contextMessageFactory.doAction(msgType, stringObjectMap);
    }


    /**
     * 服务检查接口
     *
     * @return
     */
    @GetMapping("/isWorker")
    public String isWorker() {
        return "Is Worker !";
    }
}
